'use strict'
const path = require('path');
const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000

const publicPath = path.join(__dirname, 'public');
const server = http.createServer((req, res) => {
    const fileName = path.basename(req.url);
    const filePath = path.join(publicPath, fileName);

    // res.statusCode = 200;
    if (path.extname(filePath) === '.html') {
        res.setHeader = ('Content-Type', 'text/plain');
    }

    if (!fs.existsSync(filePath)) {
        res.statusCode = 404;
        res.end();
        return;
    }
    // 异步读取
    fs.readFile(filePath, 'utf-8', (err, data) => {
        if (err) {
            res.statusCode = 500;
            res.end();
            return;
        }
        res.end(data + '\n');
    });

})

server.listen(port, hostname, () => {
    console.log(`server running at http://${hostname}:${port}`);
})